﻿using System.Web.Http;
using System.Web.Mvc;
using Monitor.Models.Interfaces;
using Monitor.Repository.UserRepository.LinqModel;

namespace Monitor.Controllers.ApiControllers
{
    /// <summary>
    /// Абстрактный класс для API контроллеров
    /// </summary>
    [System.Web.Http.Authorize()]
    public abstract class MainApiController : ApiController
    {
        #region LazyLoading IUserRepository

        private IUserRepository _userRepository;
        /// <summary>
        /// Репозиторий по работе с БД пользователей
        /// </summary>
        protected IUserRepository UserRepository
        {
            get
            {
                if (_userRepository == null)
                {
                    _userRepository = DependencyResolver.Current.GetService<IUserRepository>();
                }
                return _userRepository;
            }
        }

        #endregion

        #region LazyLoading IDataRepository
        private IDataRepository _dataRepository;
        /// <summary>
        /// Репозиторий информации от сервера
        /// </summary>
        protected IDataRepository DataRepository
        {
            get
            {
                if (_dataRepository == null)
                {
                    _dataRepository = DependencyResolver.Current.GetService<IDataRepository>();
                }
                return _dataRepository;
            }
        }
        #endregion

        #region LazyLoading ILogger
        private ILogger _logger;
        /// <summary>
        /// Логгер
        /// </summary>
        protected ILogger ErrorLogger
        {
            get
            {
                if (_logger == null)
                {
                    _logger = DependencyResolver.Current.GetService<Models.Interfaces.ILogger>();
                }
                return _logger;
            }
        }
        #endregion

        #region LazyLoading CurrentUser
        private User _currentUser;
        /// <summary>
        /// Текущий пользователь
        /// </summary>
        protected User CurrentUser
        {
            get
            {
                if (_currentUser == null && User.Identity.IsAuthenticated)
                {
                    _currentUser = UserRepository.GetUser(User.Identity.Name);
                }
                return _currentUser;
            }
        }
        #endregion

        #region Dispose
        //освобождение ресурсов
        protected override void Dispose(bool disposing)
        {
            if (UserRepository != null)
                UserRepository.Dispose();
            if (DataRepository != null)
                DataRepository.Dispose();
            base.Dispose(disposing);
        }

        #endregion

    }

}
